﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.Components;
using Aliyeye.Car.Net.UI.PopupDialog;
using Aliyeye.Car.Net.UI.Common;
using Aliyeye.Car.Net.UI.AccountsUsersModel;
using Aliyeye.Car.Net.UI.PrintExport;
using Aliyeye.Car.Net.UI.OrderModel;

namespace Aliyeye.Car.Net.UI.StatisticsModel
{
    public partial class StatisticsByReceivableDue : Aliyeye.Car.Net.UI.BaseForm
    {
        AccountsUsersSvc.SoapHeaderClass sopaHeader = new AccountsUsersSvc.SoapHeaderClass();

        private string strSearch = string.Empty;
        private DataSet dsAll = null;
        string customerCode = "";

        public StatisticsByReceivableDue()
        {
            InitializeComponent();
            DateTime dtNow = DateTime.Now;
            DateTime dt = new DateTime(dtNow.Year, dtNow.Month, 1);

            dtstarttime.Value = dt;
            dtendtime.Value = dtNow;
        }

        private void UserList_Load(object sender, EventArgs e)
        {
            BindComboBoxInfo();
            GetSearchString();
            this.pager1.PageCurrent = 1;
            this.pager1.Bind();
            GetAllInfoByCondistion();
        }

        private void BindComboBoxInfo()
        {
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ArchivesSvc.SoapHeaderClass sopaHeaderRole = new Aliyeye.Car.Net.UI.ArchivesSvc.SoapHeaderClass();

            ServiceManipulator.SafeAsyncExecution<ArchivesSvc.ArchivesServiceSoapClient>(
                proxy => proxy.ComBoxPay(sopaHeaderRole),
                result =>
                {
                    if (result.Error == null)
                    {
                        DataSet dtRole = (DataSet)result.Result;

                        DataRow dr = dtRole.Tables[0].NewRow();
                        dr["Id"] = "-1";
                        dr["Name"] = "全部";
                        dr["Namevalue"] = "全部";
                        dtRole.Tables[0].Rows.Add(dr);

                        DataView dv = dtRole.Tables[0].DefaultView;
                        dv.Sort = "id asc";

                        cmbpaytype.DisplayMember = "Namevalue";
                        cmbpaytype.ValueMember = "Id";
                        cmbpaytype.DataSource = dv;
                        cmbpaytype.SelectedIndex = 0;
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }


        private int dgvBind()
        {
            PageData pageData = new PageData(this, pager1, this.overlay);
            string _strSql = "Reserve.OrderSataus='true' and Reserve.TotalAmount !='0'";

            pageData.TableName = "Reserve left join Customer on Customer.Id=Reserve.CustId left join Car on Car.Id=Reserve.CarId left join Accounts_Users on Accounts_Users.UserID=Reserve.UserId  left join Accounts_Users DriverUser on DriverUser.UserId=Car.UserId";
            pageData.PrimaryKey = "Reserve.Id";
            pageData.OrderStr = "Reserve.InpuTime desc";
            pageData.PageIndex = this.pager1.PageCurrent;
            pageData.PageSize = this.pager1.PageSize;
            pageData.QueryCondition = _strSql + strSearch.ToString();
            pageData.QueryFieldName = "DriverUser.TrueName as DriverName, Reserve.ReceivedAmount-Reserve.TotalAmount as yingshou, Car.Code, Car.Brand, car.carType, car.TimeoutPrie, car.OvertimePrie , Reserve.* ,Customer.Name as customerName, Customer.ComName, Accounts_Users.TrueName as inputUserName";

            dgvInfo.AutoGenerateColumns = false;
            DataSet ds = pageData.QueryDataTable();
            dgvInfo.DataSource = this.pager1.bindingSource;
            return pageData.TotalCount;
        }

        private int pager1_EventPaging(EventPagingArg e)
        {
            return dgvBind();
        }

        //搜索
        private void btnSearch_Click(object sender, EventArgs e)
        {
            GetSearchString();
            this.pager1.Bind();
            GetAllInfoByCondistion();
        }

        private void GetSearchString()
        {
            string strWhere = "";
            //strWhere = " 1=1 " + strWhere;
            strWhere += " and Reserve.InpuTime BETWEEN '" + dtstarttime.Value + "' AND '" + dtendtime.Value + "'";

            if (!string.IsNullOrEmpty(txtcustcode.Text))
            {
                strWhere += " And Customer.Code like '%" + txtcustcode.Text + "%'";
            }
            if (cmbpaytype.Text.Trim() != "全部" && !string.IsNullOrEmpty(cmbpaytype.Text))
                strWhere += " and PayType='" + cmbpaytype.Text.Trim() + "' ";

            strSearch = strWhere;
        }

        private void GetAllInfoByCondistion()
        {
            //string _strSql = "1=1 ";
            string strWhere = "";
            //if (!string.IsNullOrEmpty(strSearch))
            strWhere = " where Reserve.OrderSataus='true' and Reserve.TotalAmount !='0'" + strSearch;
            string strOrderBy = " order by Reserve.InpuTime desc";
            string strSelect = "select DriverUser.TrueName as DriverName, Reserve.ReceivedAmount-Reserve.TotalAmount as yingshou, Car.Code, Car.Brand, car.carType, car.TimeoutPrie, car.OvertimePrie , Reserve.* ,Customer.Name as customerName, Customer.ComName,  Accounts_Users.TrueName as inputUserName from Reserve left join Customer on Customer.Id=Reserve.CustId left join Car on Car.Id=Reserve.CarId left join Accounts_Users on Accounts_Users.UserID=Reserve.UserId left join Accounts_Users DriverUser on DriverUser.UserId=Car.UserId ";
            string strSql = strSelect + strWhere.ToString() + strOrderBy;

            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            CarSvc.SoapHeaderClass sopaHeader = new CarSvc.SoapHeaderClass();

            ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
                proxy => proxy.GetAllListForSearchCondistion(sopaHeader, strSql),
                result =>
                {
                    if (result.Error == null)
                    {
                        dsAll = (DataSet)result.Result;

                        decimal sumWeiShou = 0;
                        decimal yingshou = 0;

                        if (dsAll != null && dsAll.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dr in dsAll.Tables[0].Rows)
                            {
                                sumWeiShou += Convert.ToDecimal(dr["TotalAmount"]);
                                yingshou += Convert.ToDecimal(dr["yingshou"]);
                            }
                        }
                        this.lblYingShou.Text = yingshou.ToString() + " 元";
                        //this.txtShiShou.Text = sumShiShou.ToString() + " 元";
                        this.lblWeiShou.Text = sumWeiShou.ToString() + " 元";
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message);
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }


        //全部
        private void btnAll_Click(object sender, EventArgs e)
        {
            strSearch = "";
            this.pager1.Bind();
            GetAllInfoByCondistion();
        }

        //返回
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvInfo.Rows.Count; )
                {
                    this.dgvInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void dgvInfoCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            e.CellStyle.WrapMode = DataGridViewTriState.True;
            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "订车类型")
            {
                if (e.Value != null)
                {
                    decimal totalAmountTemp = 0;
                    //decimal illegalRetention = 0;
                    decimal totalAmount = 0;
                    decimal receivedAmount = 0;
                    receivedAmount = Convert.ToDecimal(this.dgvInfo.Rows[e.RowIndex].Cells["实收金额"].Value);

                    if (this.dgvInfo.Rows[e.RowIndex].Cells["IsCompletedCheckout"].Value != null && this.dgvInfo.Rows[e.RowIndex].Cells["IsCompletedCheckout"].Value.ToString().ToLower().Trim() == "false")
                    {
                        totalAmountTemp = Convert.ToDecimal(this.dgvInfo.Rows[e.RowIndex].Cells["未收金额"].Value);

                        totalAmount += totalAmountTemp;
                        this.dgvInfo.Rows[e.RowIndex].Cells["未收金额"].Value = totalAmount;
                        this.dgvInfo.Rows[e.RowIndex].Cells["应收金额"].Value = receivedAmount - totalAmount;
                    }
                    else
                    {
                        this.dgvInfo.Rows[e.RowIndex].Cells["应收金额"].Value = receivedAmount;
                    }

                    if (Convert.ToInt32(e.Value) == 1)
                    {
                        e.Value = "长租自驾";
                        //this.dgvInfo.Rows[e.RowIndex].Cells["租赁时间"].Value = time.ToString() + " 月";
                    }

                    else if (Convert.ToInt32(e.Value) == 2)
                    {
                        e.Value = "短租自驾";
                        //this.dgvInfo.Rows[e.RowIndex].Cells["租赁时间"].Value = time.ToString() + " 小时";
                    }
                    else if (Convert.ToInt32(e.Value) == 3)
                    {
                        e.Value = "长租带驾";
                        //this.dgvInfo.Rows[e.RowIndex].Cells["租赁时间"].Value = time.ToString() + " 月";
                    }
                    else if (Convert.ToInt32(e.Value) == 4)
                    {
                        e.Value = "短租带驾";
                        //this.dgvInfo.Rows[e.RowIndex].Cells["租赁时间"].Value = time.ToString() + " 小时";
                    }
                }
            }

            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "日期")
            {
                if (e.Value != null)
                {
                    e.Value = Convert.ToDateTime(e.Value).Date.ToString("yyyy-MM-dd");
                }
            }

            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "时间")
            {
                if (e.Value != null)
                {
                    e.Value = Convert.ToDateTime(e.Value).Hour.ToString() + ":" + Convert.ToDateTime(e.Value).Minute.ToString();
                }
            }
        }

        private void dgvInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (IsANonHeaderButtonCell(e))
            {
                ButtonClicked(e);
            }
        }

        private bool IsANonHeaderButtonCell(DataGridViewCellEventArgs cellEvent)
        {
            if (dgvInfo.Columns[cellEvent.ColumnIndex] is
                 DataGridViewButtonColumn &&
                 cellEvent.RowIndex != -1)
            { return true; }
            else { return (false); }
        }

        private void ButtonClicked(DataGridViewCellEventArgs e)
        {
            String strButtonContent = dgvInfo.Columns[e.ColumnIndex].Name;
            int carid = 0;
            carid = Convert.ToInt32(dgvInfo.Rows[e.RowIndex].Cells["CarID"].Value.ToString());
            int reserveId = 0;
            if (dgvInfo.Rows[e.RowIndex].Cells["ReserveId"].Value != null && dgvInfo.Rows[e.RowIndex].Cells["ReserveId"].Value.ToString().Trim() != "")
                reserveId = Convert.ToInt32(dgvInfo.Rows[e.RowIndex].Cells["ReserveId"].Value.ToString());

            string type = dgvInfo.Rows[e.RowIndex].Cells["Type"].Value.ToString();

            if (strButtonContent.Trim().Equals("结账"))
            {
                if (reserveId <= 0)
                {
                    PageCommon.Alert("此车没有订车！请重新操作！");
                    return;
                }

                if (PageCommon.Confirm("确定要结账吗？"))
                {
                    switch (type.Trim())
                    {
                        case "长租自驾":
                        case "1":
                        case "短租自驾":
                        case "2":
                        case "长租带驾":
                        case "3":
                            Settlement show1 = new Settlement(Convert.ToInt32(carid), reserveId, true);
                            show1.ShowDialog();
                            break;
                        case "短租带驾":
                        case "4":
                            SettlementShort show2 = new SettlementShort(Convert.ToInt32(carid), reserveId);
                            show2.ShowDialog();
                            break;
                    }
                }
            }
            this.pager1.Bind();
        }


        private void ExportAllSearchCondistion()
        {
            try
            {
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = saveFileDialog.FileName;
                    ExcelHelper excelHelper = new ExcelHelper();
                    string msg = "";
                    if (excelHelper.StatisticsByDriverListExport(dsAll, filePath, ref msg))
                    {
                        PageCommon.Notify("文档导出成功！");
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Alert(msg);
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                }
            }
            catch
            {
                PageCommon.Notify("文档导出失败！");
                overlay.FadeOut(); Cursor.Current = Cursors.Default;
            }
        }

        //导出
        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportAllSearchCondistion();
        }

        //打印
        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                ExcelHelper excelHelper = new ExcelHelper();
                string msg = "";
                if (excelHelper.PrintStatisticsByDriverList(dsAll, ref msg))
                {
                    PageCommon.Notify("打印成功！");
                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                }
                else
                {
                    PageCommon.Alert(msg);
                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                }
            }
            catch
            {
                PageCommon.Notify("打印失败！");
                overlay.FadeOut(); Cursor.Current = Cursors.Default;
            }

        }


        private void txtcustcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string strSearch = txtcustcode.Text;
                if (string.IsNullOrEmpty(strSearch))
                {
                    DialogWarning dia = new DialogWarning("客户编号不能为空！");
                    dia.ShowDialog();
                    return;
                }
                else
                {
                    DisplayCustomeLIst(strSearch, "客户编号");
                }
            }
        }

        private void DisplayCustomeLIst(string strSearch, string type)
        {
            if (string.IsNullOrEmpty(strSearch))
            {
                return;
            }
            string strSelectWhere = "";
            if (type == "姓名")
            {
                strSelectWhere = " Name like '%" + strSearch + "%'";
            }
            if (type == "客户编号")
            {
                strSelectWhere = " Code like '%" + strSearch + "%'";
            }
            DataSet ds = null;
            dgvCustomer.DataSource = null;
            dgvCustomer.AutoGenerateColumns = false;
            CustomerSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.CustomerSvc.SoapHeaderClass();
            ServiceManipulator.SafeAsyncExecution<CustomerSvc.CustomerServiceSoapClient>(
                proxy => proxy.GetList(sopaHeader, strSelectWhere),
                result =>
                {
                    if (result.Error == null)
                    {
                        ds = (DataSet)result.Result;
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            dgvCustomer.DataSource = ds.Tables[0];
                            this.dgvCustomer.Visible = true;
                            this.dgvCustomer.Focus();
                        }
                        else
                        {
                            txtcustcode.Text = customerCode;
                            PageCommon.Alert("查找的客户不存在，请重新查找！");
                        }
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

        }

        private void dgvCustomer_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvCustomer.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvCustomer.Rows.Count; )
                {
                    this.dgvCustomer.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void dgvInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                //customerInfo.Id = Convert.ToInt32(this.dgvInfo.CurrentRow.Cells["编号"].Value.ToString());
                //customerInfo.Name = this.dgvInfo.CurrentRow.Cells[1].Value.ToString();
                //customerInfo.Tel = this.dgvInfo.CurrentRow.Cells["移动电话"].Value.ToString();
                //customerInfo.ComName = this.dgvInfo.CurrentRow.Cells["单位名称"].Value.ToString();

                this.txtcustcode.Text = this.dgvCustomer.CurrentRow.Cells[0].Value.ToString();
                this.dgvCustomer.Visible = false;
                customerCode = this.txtcustcode.Text;

                //this.txtName.Text = this.dgvInfo.CurrentRow.Cells[1].Value.ToString();
                //customID = Convert.ToInt32(this.dgvInfo.CurrentRow.Cells["编号"].Value.ToString());
                //customerName = this.txtName.Text;
                this.dtstarttime.Focus();
            }
        }
    }
}
